<template>
  <div class="page-container">
    <!-- 如果有子路由激活，则显示子路由内容 -->
    <router-view v-if="$route.name !== 'Proposal'"></router-view>
    <!-- 当前页面的主要内容，只在当前路由时显示 -->
    <div v-else v-loading="loading" element-loading-text="加载中..." :element-loading-background="'rgba(0, 0, 0, 0)'" >
      <!-- 顶部标题栏 -->
      <header class="header">
        <BackBtn />
        <h1>提案统计页面</h1>
        <Time />
      </header>

      <!-- 主要内容区域 -->
      <div class="main-content">
        <!-- 左侧容器组 -->
        <div class="left-container">
          <!-- 容器1：提案统计 -->
          <div class="statistics-container">
            <div class="stat-box">
              <div class="stat-label">提案总数:</div>
              <div class="stat-value">
                <span class="number green">{{ totalProposals }}</span>
                <span class="unit">条</span>
              </div>
              <span style="font-size: 22px; color: black; margin-bottom: 10px;">已完结提案：<span class="number red">{{ completedProposals }}</span> <span class="unit" style="font-size: 22px;">条</span></span>
            </div>
            <div class="stat-box">
              <div class="stat-label">相较昨日增加提案:</div>
              <div class="stat-value">
                <span class="number green">{{ newProposalsYesterday }}</span>
                <span class="unit">条</span>
              </div>
            </div>
          </div>

          <!-- 容器2：待审核和操作按钮 -->
          <div class="action-container">
            <div class="container-title">
              <div class="line"></div>
              <h3>提案管理</h3>
            </div>
            <div class="stat-box">
        
            </div>
            <div class="action-buttons">
              <el-button v-for="btn in actionButtons" :key="btn.name" type="danger" class="action-btn"
                @click="btn.handler">
                {{ btn.label }}
              </el-button>
            </div>
          </div>
        </div>

        <!-- 右侧饼图 -->
        <div class="right-container">
          <!-- 容器3：用户构成饼图 -->
          <div class="pie-chart-container">
            <div class="chart-container" ref="pieChartRef"></div>
            <!-- 添加总条数显示 -->
            <div class="total-proposals">
              <p>提案类型构成</p>
              <span class="number green">{{ totalProposals }}</span>条
            </div>
          </div>
        </div>
      </div>

      <!-- 底部趋势图 -->
      <div class="bottom-container">
        <!-- 容器4：用户变化记录 -->
        <div class="trend-container">
          <div class="trend-header">
            <div class="container-title" style="margin-left: 10px;">
              <div class="line"></div>
              <h3>提案变化记录</h3>
            </div>
            <div class="trend-actions">
              <el-button type="danger" :loading="exportLoading" @click="exportTrendData">
                {{ exportLoading ? '导出中...' : '导出详表' }}
              </el-button>
              <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
                end-placeholder="结束日期" @change="handleDateRangeChange" />
            </div>
          </div>
          <div class="trend-chart" ref="trendChartRef"></div>
          
          <!-- 添加操作提示 -->
          <transition name="fade">
            <div v-if="trendChartGuide && dateRange && dateRange.length === 2" class="chart-guide">
              <div class="guide-content">
                <el-icon class="close-icon" @click="closeTrendGuide"><Close /></el-icon>
                <h4>图表操作提示：</h4>
                <ul>
                  <li style="color: brown;"><el-icon><Star /></el-icon> 在操作以下提示时需要先点击一下刷新功能键</li>
                  <li><el-icon><ZoomIn /></el-icon> 拖动底部滑动条两端红色手柄可查看局部数据</li>
                  <li><el-icon><Connection /></el-icon> 直接滚动鼠标滚轮可以缩放图表</li>
                  <li><el-icon><Pointer /></el-icon> 按住鼠标左键拖动可平移图表</li>
                  <li><el-icon><Setting /></el-icon> 点击右上角工具图标可刷新或保存图表</li>
                </ul>
              </div>
            </div>
          </transition>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ArrowLeft, ZoomIn, Connection, Pointer, Close, Setting, Star } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { useProposalStore } from '@/stores/proposal'
import { getProposalStatistics, getProposalTypeDistribution, getProposalTrend, exportProposalTrendData } from '@/api/proposal'
import { ElMessage } from 'element-plus'
import Time from '@/components/Time.vue'
import BackBtn from '@/components/Back-btn.vue'

const loading=ref(false)
const router = useRouter()
const pieChartRef = ref(null)
const trendChartRef = ref(null)
const dateRange = ref([])
// 添加导出加载状态
const exportLoading = ref(false)
// 添加趋势图操作提示
const trendChartGuide = ref(true)

// 保存图表实例的引用
const pieChartInstance = ref(null)
const trendChartInstance = ref(null)

// 提案统计数据
const totalProposals = ref(0)
const newProposalsYesterday = ref(0)
const completedProposals = ref(0)

// 操作按钮配置
const proposalStore = useProposalStore()

const actionButtons = [
  { 
    name: 'audit', 
    label: '初审', 
    handler: () => {
      proposalStore.pageStatus = 1
      router.push({ name: 'ProposalFirstAudit' })
    }
  },
  { 
    name: 'recheck', 
    label: '复审', 
    handler: () => {
      proposalStore.pageStatus = 2
      router.push({ name: 'ProposalRecheck' })
    }
  },
  { 
    name: 'shunt', 
    label: '分流处理', 
    handler: () => {
      proposalStore.pageStatus = 3
      router.push({ name: 'ProposalShunt' })
    }
  },
  { 
    name: 'reply', 
    label: '最终批复', 
    handler: () => {
      proposalStore.pageStatus = 4
      router.push({ name: 'ProposalReply' })
    }
  },
  { 
    name: 'supervision', 
    label: '督办', 
    handler: () => {
      proposalStore.pageStatus = 5
      router.push({ name: 'ProposalSupervision' })
    }
  },
  { 
    name: 'query', 
    label: '查询提案', 
    handler: () => {
      proposalStore.pageStatus = 6
      router.push({ name: 'ProposalQuery' })
    }
  }
]

// 添加重试相关的常量
const MAX_RETRIES = 3;  // 最大重试次数
const RETRY_DELAY = 1000;  // 重试延迟时间（毫秒）

// 添加延迟函数
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

// 添加带重试的请求函数
const fetchWithRetry = async (fetchFn, retries = MAX_RETRIES) => {
  try {
    return await fetchFn();
  } catch (error) {
    if (retries > 0 && error.code === 'ECONNABORTED') {
      await delay(RETRY_DELAY);
      return fetchWithRetry(fetchFn, retries - 1);
    }
    throw error;
  }
};

// 修改获取提案统计数据的函数
const fetchProposalStatistics = async () => {
  try {
    const { data } = await fetchWithRetry(async () => {
      return await getProposalStatistics();
    });
    totalProposals.value = data.totalProposals;
    newProposalsYesterday.value = data.newProposalsYesterday;
    completedProposals.value = data.completedProposals;
  } catch (error) {
    console.error('获取提案统计数据失败:', error);
    ElMessage.error('获取数据超时，请稍后再试');
    throw error;
  }
};

// 修改初始化饼图函数
const initPieChart = async () => {
  if (!pieChartRef.value) return;
  
  if (pieChartInstance.value) {
    pieChartInstance.value.dispose();
  }

  pieChartInstance.value = echarts.init(pieChartRef.value);
  try {
    const { data } = await fetchWithRetry(async () => {
      return await getProposalTypeDistribution();
    });
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c}条 ({d}%)'
      },
      series: [
        {
          type: 'pie',
          radius: ['35%', '65%'],
          center: ['50%', '50%'],
          avoidLabelOverlap: true,
          label: {
            show: true,
            position: 'outside',
            formatter: '{b}\n{c}条 ({d}%)',
            fontSize: 13,
            lineHeight: 16,
            alignTo: 'edge',
            edgeDistance: '10%',
            overflow: 'truncate'
          },
          labelLine: {
            length: 15,
            length2: 10,
            smooth: true,
            minTurnAngle: 90
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 14,
              fontWeight: 'bold'
            }
          },
          data: data
        }
      ]
    }
    pieChartInstance.value.setOption(option);
  } catch (error) {
    console.error('获取提案类型分布数据失败:', error);
    ElMessage.error('获取图表数据超时，请稍后再试');
  }
};

// 监听日期区间变化并更新图表
watch(dateRange, async (newValue) => {
  if (newValue && newValue.length === 2) {
    await updateTrendChart();
    
    // 日期变化后，强制触发restore操作并确保图表正确显示
    if (trendChartInstance.value) {
      setTimeout(() => {
        console.log('触发图表restore操作');
        trendChartInstance.value.dispatchAction({
          type: 'restore'
        });
        // 再次触发resize确保渲染正常
        trendChartInstance.value.resize();
      }, 300); // 增加延迟时间，确保操作在图表完全加载后执行
    }
  }
}, { deep: true });

// 关闭操作提示
const closeTrendGuide = () => {
  trendChartGuide.value = false;
};

// 修改初始化趋势图函数
const initTrendChart = async () => {
  if (!trendChartRef.value) return;
  
  // 确保销毁旧的实例
  if (trendChartInstance.value) {
    trendChartInstance.value.dispose();
    trendChartInstance.value = null;
  }

  // 创建新的实例
  trendChartInstance.value = echarts.init(trendChartRef.value);

  try {
    // 从日期范围中提取开始和结束日期
    let startDate = null;
    let endDate = null;
    if (dateRange.value && dateRange.value.length === 2) {
      startDate = formatDate(dateRange.value[0]);
      endDate = formatDate(dateRange.value[1]);
    }

    const { data } = await fetchWithRetry(async () => {
      return await getProposalTrend(startDate, endDate);
    });
    
    // 确保数据格式正确
    let chartData = data || [];
    if (chartData.length === 0) {
      chartData = [{ date: '暂无数据', value: 0 }];
    }
    
    console.log('获取到数据点数量:', chartData.length);

    // 计算日期数量，决定是否显示滚动条
    const dateCount = chartData.length;
    const showDataZoom = dateCount > 15;
    
    // 计算合适的y轴最大值，确保图表有足够的高度
    const maxValue = Math.max(...chartData.map(item => Number(item.value)));
    const yAxisMax = maxValue > 0 ? Math.ceil(maxValue * 1.2) : 1; // 留出20%的空间
    
    const option = {
      animation: true,
      tooltip: {
        trigger: 'axis',
        formatter: '{b}<br/>{a}: {c}条',
        axisPointer: {
          type: 'line',
          snap: true
        },
        confine: true, // 确保提示框不会超出画布
      },
      grid: {
        top: '10%',
        left: '3%',
        right: '4%',
        bottom: showDataZoom ? 60 : 20, // 根据是否显示滚动条调整底部留白
        containLabel: true
      },
      toolbox: {
        feature: {
          dataZoom: {
            yAxisIndex: 'none',
            title: {
              zoom: '区域缩放',
              back: '还原'
            }
          },
          restore: {
            title: '刷新'
          },
          saveAsImage: {
            title: '保存为图片'
          }
        },
        right: 20,
        top: 0
      },
      dataZoom: [
        {
          type: 'slider',
          show: showDataZoom, // 只有当数据点超过15个时才显示滚动条
          start: 0,
          end: 100,
          height: 30,
          bottom: 10,
          borderColor: '#c62828',
          backgroundColor: '#f5f5f5',
          fillerColor: 'rgba(198, 40, 40, 0.2)',
          handleIcon: 'path://M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
          handleSize: '100%',
          handleStyle: {
            color: '#c62828',
            shadowBlur: 3,
            shadowColor: 'rgba(0, 0, 0, 0.3)',
            shadowOffsetX: 2,
            shadowOffsetY: 2
          },
          textStyle: {
            color: '#333'
          }
        },
        {
          type: 'inside',
          start: 0,
          end: 100,
          zoomOnMouseWheel: true, // 允许鼠标滚轮缩放
          moveOnMouseMove: true, // 允许鼠标拖动平移
          disabled: !showDataZoom // 当日期少于15天时禁用内部缩放
        }
      ],
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: chartData.map(item => item.date),
        axisLabel: {
          interval: 'auto', // 自动计算间隔
          rotate: 45,
          formatter: function(value) {
            return value.split(' ')[0];
          },
          textStyle: {
            fontSize: 12,
            align: 'right'
          },
          margin: 15,
          hideOverlap: true
        },
        axisTick: {
          alignWithLabel: true,
          interval: 'auto'
        },
        axisLine: {
          lineStyle: {
            color: '#666'
          }
        },
        splitLine: {
          show: false
        }
      },
      yAxis: {
        type: 'value',
        name: '条',
        min: 0, // 始终从0开始
        max: yAxisMax, // 动态计算最大值
        minInterval: 1,
        nameTextStyle: {
          padding: [0, 0, 0, 30]
        },
        splitLine: {
          lineStyle: {
            type: 'dashed',
            color: '#ddd'
          }
        },
        axisLabel: {
          fontSize: 14
        },
        axisLine: {
          show: true,
          lineStyle: {
            color: '#666'
          }
        }
      },
      series: [
        {
          name: '提案数量',
          data: chartData.map(item => Number(item.value)),
          type: 'line',
          smooth: true,
          sampling: 'average',
          showSymbol: true,
          symbolSize: 8,
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0, color: 'rgba(198, 40, 40, 0.5)'
              }, {
                offset: 1, color: 'rgba(198, 40, 40, 0.05)'
              }]
            }
          },
          lineStyle: {
            width: 4,
            color: '#c62828'
          },
          itemStyle: {
            color: '#c62828',
            borderWidth: 2,
            borderColor: '#fff',
            shadowColor: 'rgba(0, 0, 0, 0.3)',
            shadowBlur: 3
          },
          emphasis: {
            itemStyle: {
              borderWidth: 3,
              borderColor: '#fff',
              shadowBlur: 5,
              shadowColor: 'rgba(198, 40, 40, 0.5)'
            }
          }
        }
      ]
    };
    
    // 清空之前的配置
    trendChartInstance.value.clear();
    // 设置新的配置
    trendChartInstance.value.setOption(option, true);
    
    // 确保图表在视图更新后重新绘制
    setTimeout(() => {
      if (trendChartInstance.value) {
        trendChartInstance.value.resize();
      }
    }, 50);
  } catch (error) {
    console.error('获取提案趋势数据失败:', error);
    ElMessage.error('获取趋势图数据超时，请稍后再试');
  }
};

// 添加更新趋势图的方法
const updateTrendChart = async () => {
  loading.value = true;
  try {
    await initTrendChart();
  } catch (error) {
    console.error('更新趋势图失败:', error);
  } finally {
    loading.value = false;
  }
}

// 处理导出趋势数据
const exportTrendData = async () => {
  if (exportLoading.value) return;
  exportLoading.value = true;
  
  try {
    let startDate = null;
    let endDate = null;
    if (dateRange.value && dateRange.value.length === 2) {
      startDate = formatDate(dateRange.value[0]);
      endDate = formatDate(dateRange.value[1]);
    }
    
    console.log('导出趋势数据参数:', { startDate, endDate });
    
    const response = await exportProposalTrendData(startDate, endDate);
    
    // 检查响应
    if (!response || response.size === 0) {
      throw new Error('导出的文件为空');
    }
    
    // 检查响应类型
    const contentType = response.type;
    if (!contentType.includes('spreadsheetml.sheet')) {
      // 如果响应不是Excel文件，尝试读取错误信息
      const text = await response.text();
      throw new Error(text || '导出的文件格式不正确');
    }
    
    // 创建下载链接
    const blob = new Blob([response], { type: contentType });
    const downloadUrl = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = downloadUrl;
    link.download = `提案变化趋势数据_${new Date().toLocaleDateString()}.xlsx`;
    document.body.appendChild(link);
    link.click();
    
    // 清理资源
    window.URL.revokeObjectURL(downloadUrl);
    document.body.removeChild(link);
    
    ElMessage.success('导出成功');
  } catch (error) {
    console.error('导出失败:', error);
    ElMessage.error(error.message || '导出失败');
  } finally {
    exportLoading.value = false;
  }
};

// 格式化日期函数
const formatDate = (date) => {
  if (!date) return null;
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

// 处理日期范围变化
const handleDateRangeChange = () => {
  initTrendChart();
};

// 修改初始化数据的方法
const initializeData = async () => {
  loading.value = true;
  try {
    await fetchProposalStatistics();
    await nextTick();
    // 确保DOM已经更新
    await new Promise(resolve => setTimeout(resolve, 100));
    await Promise.all([
      initPieChart(),
      initTrendChart()
    ]);
  } catch (error) {
    console.error('初始化失败:', error);
  } finally {
    loading.value = false;
  }
};

// 处理路由进入的处理函数
const handleRouteEnter = async () => {
  if (router.currentRoute.value.name === 'Proposal') {
    loading.value = true
    await initializeData()
    loading.value = false
  }
}

// 添加路由监听
watch(() => router.currentRoute.value.name, async (newRouteName) => {
  if (newRouteName === 'Proposal') {
    loading.value = true
    await initializeData()
    loading.value = false
  }
})

// 处理窗口大小变化
const handleResize = () => {
  if (pieChartInstance.value) {
    pieChartInstance.value.resize({
      animation: {
        duration: 300
      }
    });
  }
  if (trendChartInstance.value) {
    trendChartInstance.value.resize({
      animation: {
        duration: 300
      }
    });
  }
}

onMounted(async () => {
  // 初始化数据
  if (router.currentRoute.value.name === 'Proposal') {
    loading.value = true
    await initializeData()
    loading.value = false
  }
  
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})

// 组件卸载前清理
onBeforeUnmount(() => {
  // 移除事件监听
  window.removeEventListener('resize', handleResize)
  
  // 销毁图表实例
  if (pieChartInstance.value) {
    pieChartInstance.value.dispose()
    pieChartInstance.value = null
  }
  if (trendChartInstance.value) {
    trendChartInstance.value.dispose()
    trendChartInstance.value = null
  }
})
</script>

<style scoped>
@import '@/assets/css/index/proposal.css';
@import '@/assets/css/header/index.css';
@import '@/assets/css/proposal/chart.css';
</style> 